<template>
  <div class="qa-wrapper">
    <div class="wrapper-header">
      <div class="switch">
        <!-- 筛选项 -->
        <el-select style="width: 170px" v-model="selectedStatus" placeholder="任务状态" @change="fetchRecords">
          <el-option v-for="status in statusOptions" :key="status.value" :label="status.label" :value="status.value" />
        </el-select>
        <!-- 日期选择控件 -->
        <el-date-picker
          style="margin-left: 10px; width: 300px"
          v-model="selectedDate"
          type="date"
          :shortcuts="shortcuts"
          value-format="YYYY-MM-DD"
          placeholder="选择日期"
          @change="fetchRecords"
        />
        <span style="margin-left: 5px"><el-input v-model="findUserName" placeholder="输入姓名搜索"></el-input></span>
        <span style="margin-left: 5px"><el-input v-model="findUserMobile" placeholder="输入手机搜索"></el-input></span>
      </div>
      <div class="search">
        <el-button @click="fetchRecords" type="primary">查询</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="currentTaskRecords" style="width: 100%" :row-class-name="tableRowClassName">
      <el-table-column type="expand">
        <template #default="props">
          <el-descriptions style="margin-left: 10px" title="任务详情" :column="3" border>
            <el-descriptions-item label="用户 ID">{{ props.row.userId || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="用户姓名">{{ props.row.username || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="用户手机">{{ props.row.phone || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="当前周期开始日期">{{
              props.row.periodStartDate || '暂无信息'
            }}</el-descriptions-item>
            <el-descriptions-item label="当前周期结束日期">{{
              props.row.periodEndDate || '暂无信息'
            }}</el-descriptions-item>
            <el-descriptions-item label="实际还款日期">{{
              props.row.actualRepaymentDate || '暂无信息'
            }}</el-descriptions-item>
            <el-descriptions-item label="每期本金">{{ props.row.principal || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="每期利息">{{ props.row.interest || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="总还款金额">{{ props.row.totalAmount || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="逾期金额">{{ props.row.overdueAmount || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ props.row.remark || '暂无备注' }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>

      <el-table-column label="用户信息" prop="username">
        <template #default="props">
          <div>
            <span style="text-align: center">{{ props.row.username }}</span>
            <br />
            <el-tag type="info">{{ props.row.phone }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="期数">
        <template #default="props">
          <span>第{{ props.row.installmentNumber }}期 （共{{ props.row.totalWeekNum }}期）</span>
        </template>
      </el-table-column>
      <el-table-column label="总额">
        <template #default="props">
          {{ props.row.totalAmount }}
          <span v-if="calculateOverdueAmount(props.row) > 0"
            ><br />
            <el-tag type="danger">预计产生{{ calculateOverdueAmount(props.row) }}逾期费用</el-tag></span
          >
        </template>
      </el-table-column>
      <el-table-column label="还款周期">
        <template #default="props">
          <div style="text-align: center; height: 80px; margin-top: 8px">
            <el-timeline>
              <el-timeline-item color="#0bbd87">{{ props.row.periodStartDate }}</el-timeline-item>
              <el-timeline-item :color="props.row.status === 'PAID' ? '#0bbd87' : 'red'">{{
                props.row.periodEndDate
              }}</el-timeline-item>
            </el-timeline>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="props">
          <el-tag :type="getStatusTag(props.row.status)">{{ getStatusLabel(props.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间">
        <template #default="props">
          <span v-if="props.row.updatedAt">{{ formatISOTimeByValue(props.row.updatedAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openStatusDialog(scope.row)">修改状态</el-button>
          <el-button type="danger" size="small" @click="deleteRecord(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-left: 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="sizes, prev, pager, next, jumper"
      :total="total"
    />
    <el-dialog v-model="statusDialogVisible" title="修改状态">
      <el-form :model="selectedRecord" v-if="selectedRecord" label-position="right">
        <el-form-item label="当前状态：">
          <span>{{ getStatusLabel(selectedRecord.status) }}</span>
        </el-form-item>
        <el-form-item label="新状态：">
          <el-select v-model="newStatus" placeholder="请选择状态">
            <el-option
              v-for="status in statusOptions.filter((s:any) => s.value)"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="还款时间：" v-if="newStatus === 'PAID'">
          <el-date-picker v-model="repaymentDate" type="date" placeholder="选择日期："> </el-date-picker>
        </el-form-item>
        <el-form-item label="逾期金额：" v-if="newStatus === 'OVERDUE'">
          <el-input v-model="overdueAmount" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmModifyStatus">提交</el-button>
      </template>
    </el-dialog>
    <AdminKeyDialog ref="adminKeyDialog"></AdminKeyDialog>
  </div>
</template>
<style scoped>
@import '../style/applyReview.less';
</style>
<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ApplyModule } from '@/services/modules/apply' // 请根据实际路径修改
import { formatISOTimeByValue, isOverdue, calculateOverdueAmount } from '@/utils/helper' // 请根据实际路径修改
import * as httpService from '@/services/apply.service'
import AdminKeyDialog from './AdminKeyDialog.vue'
import { useUserStore } from '@/stores/useStore'

const adminKeyDialog = ref<InstanceType<typeof AdminKeyDialog>>()

// 打开管理员密钥对话框并获取密钥
const openAdminKeyDialog = () => {
  if (!useUserStore().authInfo?.opCode) {
    adminKeyDialog.value?.show()
    return false
  } else {
    return true
  }
}

// 任务记录
const taskRecords = ref<ApplyModule.TaskVo[]>([])
const currentTaskRecords = ref<ApplyModule.TaskVo[]>([])
const selectedStatus = ref('')
const selectedDate = ref<string | undefined>(undefined)

const tableRowClassName = computed(() => {
  return 'success-row'
})

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '未还款', value: 'UNPAID' },
  { label: '已还款', value: 'PAID' },
  { label: '逾期', value: 'OVERDUE' },
  { label: '已关闭', value: 'CLOSE' },
]

const shortcuts = [
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '今天',
    value: () => {
      const date = new Date()
      return date
    },
  },
  {
    text: '明天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '后天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 2)
      return date
    },
  },
  {
    text: '一周后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      return date
    },
  },
]

// 当前选中要修改状态的记录
const selectedRecord = ref<ApplyModule.TaskVo | null>(null)
// 控制状态修改弹窗的显示与隐藏
const statusDialogVisible = ref(false)
// 新选择的状态
const newStatus = ref('')
const findUserName = ref('')
const findUserMobile = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(true)

// 还款时间
const repaymentDate = ref<string | undefined>(undefined)
const overdueAmount = ref(700)
// 获取状态文本
const getStatusLabel = (cellValue: string) => {
  const option = statusOptions.find((s) => s.value === cellValue)
  return option ? option.label : '未知'
}

// 获取状态颜色
const getStatusTag = (status: string) => {
  const statusMap = {
    UNPAID: 'warning',
    PAID: 'success',
    OVERDUE: 'danger',
  } as any
  return statusMap[status] || 'info'
}

// 打开状态修改弹窗
const openStatusDialog = (record: ApplyModule.TaskVo) => {
  const hasOpCode = openAdminKeyDialog()
  if (!hasOpCode) {
    return
  }
  selectedRecord.value = record
  newStatus.value = record.status
  statusDialogVisible.value = true
}

const deleteRecord = async (record: ApplyModule.TaskVo) => {
  const hasOpCode = openAdminKeyDialog()
  if (!hasOpCode) {
    return
  }
  const opCode = useUserStore().authInfo?.opCode || ''
  ElMessageBox.confirm('确认要删除该此任务吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      try {
        if (record && record.id) {
          await httpService.deleteTaskRecord(record.id, opCode)
          ElMessage.success('删除成功')
          fetchRecords()
        }
      } catch (error) {
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      ElMessage.info('操作已取消')
    })
}

// 确认修改状态
const confirmModifyStatus = async () => {
  const hasOpCode = openAdminKeyDialog()
  if (!hasOpCode) {
    return
  }
  const opCode = useUserStore().authInfo?.opCode || ''
  if (!selectedRecord.value || !selectedRecord.value.id) return
  if (!repaymentDate.value && newStatus.value === 'PAID') {
    ElMessage.error('请选择还款时间')
    return
  }
  if (newStatus.value === selectedRecord.value.status) {
    ElMessage.info('状态未改变，无需修改')
    statusDialogVisible.value = false
    return
  }
  if (!newStatus.value) {
    return ElMessage.error('状态不能为空')
  }
  const recordId = selectedRecord.value.id

  try {
    // 二次确认
    await ElMessageBox.confirm(
      `确定将【${getStatusLabel(selectedRecord.value.status)}】 修改为 【${getStatusLabel(newStatus.value)}】 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用修改任务状态的 API
    await httpService.modifyTaskRecordStatus({
      taskId: selectedRecord.value.id,
      status: newStatus.value,
      actualRepaymentDate: repaymentDate.value,
      overdueAmount: overdueAmount.value,
      opCode: opCode,
    })
    repaymentDate.value = undefined
    // 更新当前选中记录的状态
    selectedRecord.value.status = newStatus.value as any

    // 更新表格中的对应记录状态
    const recordIndex = currentTaskRecords.value.findIndex((task) => task.id === recordId)
    if (recordIndex !== -1) {
      currentTaskRecords.value[recordIndex].status = newStatus.value as any
    }

    ElMessage.success('任务状态修改成功')
    statusDialogVisible.value = false
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message || '修改任务状态失败，请稍后重试')
    } else {
      ElMessage.error('修改任务状态失败，请稍后重试')
    }
    statusDialogVisible.value = false
  }
}

// 获取任务记录
const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await httpService.searchTaskRecords({
      name: findUserName.value,
      phone: findUserMobile.value,
      status: selectedStatus.value,
      page: currentPage.value - 1,
      size: pageSize.value,
      dateTime: selectedDate.value,
    })
    const pageData = response.data
    taskRecords.value = pageData.list
    currentPage.value = pageData.currentPage
    pageSize.value = pageData.pageSize
    total.value = pageData.total
    currentTaskRecords.value = taskRecords.value
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message || '获取任务记录失败，请稍后重试')
    } else {
      ElMessage.error('获取任务记录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 分页相关方法
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  handleCurrentChange(1)
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  fetchRecords()
}

onMounted(() => {
  selectedStatus.value = ''
  repaymentDate.value = undefined
  selectedDate.value = undefined
  fetchRecords()
})
</script>
